package com.tanhua.admin.listener;

/**
 * @author SunSun
 * @date 2021/11/5
 */

import com.tanhua.autoconfig.template.AliyunGreenTemplate;
import com.tanhua.dubbo.api.MovementApi;
import com.tanhua.model.mongo.Movement;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
public class AuditListener {

    @DubboReference
    private MovementApi movementApi;

    @Autowired
    private AliyunGreenTemplate template;

    @RabbitListener(
            bindings = @QueueBinding(
                    value = @Queue(
                            value = "tanhua.audit.queue",
                            durable = "true"
                    ),
                    exchange = @Exchange(
                            value = "tanhua.audit.exchange",
                            type = ExchangeTypes.TOPIC
                    ),
                    key = "audit.movement"
            )
    )
    public void audit(String movementId) {
        try {
            Movement movement = movementApi.findOne(movementId);

            Map<String, String> TextScan = template.greenTextScan(movement.getTextContent());

            Map<String, String> imageScan = template.imageScan(movement.getMedias());

            int state = 0;
            if (TextScan != null && imageScan != null) {
                String textSuggestion = TextScan.get("suggestion");
                String imageSuggestion = imageScan.get("suggestion");
                if ("block".equals(textSuggestion) || "block".equals(imageSuggestion)) {
                    state = 2;
                } else if ("pass".equals(textSuggestion) && "pass".equals(imageSuggestion)) {
                    state = 1;
                }
            }
            movementApi.update(movementId,state);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
